<div id="postOpt" class="table-responsive">
    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#postModal">
        <span class="glyphicon glyphicon-plus"></span>&nbsp;添加
    </button>
</div>
<div id="postList">
    <table class="table table-striped table-hover">
        <thead>
        <tr>
            <th>标题</th>
            <th>标签</th>
            <th>发布时间</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>

        </tbody>
    </table>
    <div class="form-group">
        <button id="loadNextPageBtn" class="btn btn-primary form-control"><input type="hidden" name="" id="pageIndex" value="1"/><span id="loadTip">加载更多</span></button>
    </div>

    <span class="fix-height"></span>
</div>

<!-- Modal -->
<div class="modal fade" id="postModal" tabindex="-1" role="dialog" aria-labelledby="postModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-editor">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                        aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">写文章</h4>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-8">
                        <div class="form-group">
                            <label for="postTitle">标题</label>
                            <input type="text" class="form-control" id="postTitle">
                            <input type="hidden" name="" id="postId"/>
                            <input type="hidden" name="" id="postContent"/>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="postTag">标签</label>
                            <input type="text" class="form-control" id="postTag">
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-12">
                        <!--<div id="postEditor"> <textarea style="display:none;"></textarea></div>-->
                        <iframe id="postContentIframe" src="#" name="postContentIframe" frameborder="0" width="100%" height="620" scrolling="no"></iframe>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="savePost">保存</button>
            </div>
        </div>
    </div>
</div>
<script>
    $(function () {
        $postModal = $('#postModal');

        var fetchPosts = function (page) {
            if(page == 1){
                $('#postList').find('tbody').children().remove();
            }
            $('#postId').val('');
            $('#postTitle').val('');
            $('#postTag').val('');
            $.get('/i/posts/list/'+page, function (posts) {
                var rows = [];
                if (posts && posts.length > 0) {
                    for (var i = 0; i < posts.length; i++) {
                        rows.push('<tr><td>' + vlidField(posts[i].title) + '</td><td>' + vlidField(posts[i].tag) + '</td><td>' + $.dateFormat(posts[i].publishAt) + '</td><td><button class="btn btn-success post-update" data-toggle="modal" data-target="#postModal"><input type="hidden" name="" value="' + posts[i].id + '" /><span class="glyphicon glyphicon-pencil"></span>&nbsp;修改</button> <button href="javascript:void(0);" class="btn btn-danger post-delete"><input type="hidden" name="" value="' + posts[i].id + '" /><span class="glyphicon glyphicon-minus"></span>&nbsp;删除</button></td></tr>')
                    }
                    $('#postList').find('tbody').append(rows);

                    $('.post-delete').on('click', function () {
                        var $this = $(this);
                        var postId = $this.find('input[type="hidden"]:eq(0)').val();
                        $.ajax({
                            url: '/admin/post/delete/' + postId,
                            contentType: 'applcation/json',
                            type: 'DELETE',
                            cache: false,
                            success: function (res) {
                                if (res.success) {
                                    $this.parent().parent().remove();
                                } else {
                                    alert(res.msg);
                                }
                            }
                        });
                    });
                } else {
                    $('#loadTip').text('已全部加载完毕');
                }
            });
        };

        $('#loadNextPageBtn').on('click', function(){
            var $pageIndex = $('#pageIndex');
            var nextPage = parseInt($pageIndex.val()) + 1;
            $pageIndex.val(nextPage);
            fetchPosts(nextPage);
        });
        fetchPosts(parseInt($('#pageIndex').val()));

        $postModal.on('show.bs.modal', function (event) {
            $('#postContentIframe').attr('src', '/admin/write');
            var $button = $(event.relatedTarget);
            if ($button.attr('class').indexOf("post-update") > 0) {
                var postId = $button.find('input[type="hidden"]:eq(0)').val();
                $.get('/i/posts/' + postId, function (res) {
                    if (res.success) {
                        var post = res.data.post;
                        $('#postId').val(postId);
                        $('#postTitle').val(vlidField(post.title));
                        $('#postTag').val(vlidField(post.tag));
                        $('#postContent').val(post.content);
                    } else {
                        alert(res.msg);
                    }

                });
            } else {
                $('#postId').val('');
                $('#postTitle').val('');
                $('#postTag').val('');
                $('#postContent').val('');
            }

        });

        $('#savePost').on('click', function () {
            var editorContentArea = $(window.frames["postContentIframe"].document).find("#editormd>textarea");
            var content = editorContentArea.val();
            if($.trim(content) == ''){
                alert('内容不能为空');
                return;
            }
            var post = {
                id: $('#postId').val(),
                title: vlidField($('#postTitle').val()),
                tag: vlidField($('#postTag').val()),
                content: content
            };
            $.ajax({
                url: '/admin/post/save',
                contentType: 'applcation/json',
                type: 'POST',
                data: JSON.stringify(post),
                cache: false,
                success: function (res) {
                    if (res.success) {
                        $postModal.modal('hide');
                        var $pageIndex = $('#pageIndex');
                        editorContentArea.val('');
                        $pageIndex.val(1);
                        fetchPosts(parseInt($pageIndex.val()));
                    } else {
                        alert(res.msg);
                    }
                }
            })
        });

        $postModal.on('shown.bs.modal', function (e) {
            $(this).find('.editor__menu--edit').click();
            $(this).find('.editor__menu--live').click();
        })
    });
</script>